<template>
  <div class="tablecontent">
    <el-card shadow="never"
             v-loading="dataLoading"
             class="aui-card--fill">

      <ejs-grid :dataSource="comDataList.retdata"
                :rowDataBound="rowDataBound"
                v-if="comDataList.retdata&&comDataList.retdata.length"
                :allowFiltering="gadgetSetting.allowFiltering"
                :filterSettings="gadgetSetting.filterSettings"
                :allowPaging="gadgetSetting.allowPaging"
                :toolbar="gadgetSetting.toolbar"
                :height="gadgetSetting.height"
                :allowSorting="gadgetSetting.allowSorting"
                :pageSettings="gadgetSetting.pageSettings"
                :queryCellInfo='customiseCell'
                :showColumnChooser="gadgetSetting.showColumnChooser"
                ref="datagrid"
                :dataBound="dataBound"
                :toolbarClick='toolbarClick'
                :allowExcelExport='gadgetSetting.allowExcelExport'
                :allowPdfExport='gadgetSetting.allowPdfExport'
                :allowResizing="gadgetSetting.allowResizing"
                :allowTextWrap='true'
                :textWrapSettings='wrapSettings'
                :actionComplete='actionComplete'
                :frozenColumns='3'>
        <e-columns>
          <e-column v-for="(columnItem, index) of comDataList.columns"
                    :key="index"
                    :maxWidth="columnItem==='Title'?'200px':''"
                    :template='columnItem==="Ticket  ID"&& nextTicketType.replace("dataset","")  === "nextTicket" ? CWTicketNumberFormartName :
                         columnItem==="Ticket  Number"&& nextTicketType.replace("dataset","")  === "autotask"? AuToTicketNumberFormartName :
                         columnItem==="Ticket Number"&& nextTicketType.replace("dataset","")  === "kaseyabms"? kaseyabmsTicketNumberFormartName :
                         columnItem==="Ticket Number"&& nextTicketType.replace("dataset","")  === "syncro"? SyncroTicketNumberFormartName :
                         columnItem==="Resolved Date"&& nextTicketType.replace("dataset","")  === "autotask"? TimeFormatName :
                         columnItem==="Id"&& nextTicketType.replace("dataset","")  === "halo"? HaloTicketNumberFormartName :
                         columnItem==="Key"&& nextTicketType.replace("dataset","")  === "jira"? JiraTicketNumberFormartName : ""'
                    :field='columnItem'
                    :visible="visibleColumn(columnItem)"
                    :foreignKeyField="columnItem"
                    :autoFit='false'
                    textAlign='Left'
                    :headerText='columnItem'>
          </e-column>
        </e-columns>

      </ejs-grid>
    </el-card>
  </div>
</template>

<script>

import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import FormartName from './format/CWTicketNumberFormartName'
import AuFormartName from './format/AutoTaskTicketNumberFormartName'
import syncroFormartName from './format/syncroTicketIDFormartName2'
import jiraFormartName from './format/jiraTicketIDFormartName'
import haloFormartName from './format/haloTicketIDFormartName'
import kaseyabmsTicketNumberFormartName from './format/kaseyabmsTicketNumberFormartName'
import { GlobalTimeformat,GlobalDateformat } from '@/utils/common'
import timeFormat from './format/TimeFormat'
import store from '@/store'
import JsPDF from 'jspdf'
export default {
  mixins: [mixinGadgetViewModule],
  props: {
    nextTicketAllInfo: {
      type: Array,
      default: function () {
        return []
      }
    },
    conditionFieldList: {
      type: Array,
      default: function () {
        return []
      }
    },
    ruleList: {
      type: Array,
      default: function () {
        return []
      }
    },
    nextTicketType: {
      type: String,
      default: null
    },
    pts: {
      type: Object,
      default: null
    },
    dataLoading: {
      type: Boolean,
      default: false
    },
    customer: {
      type: Object
    },
    nextTicketGadgetSetting: {
      type: Object
    }
  },
  data () {
    return {
      CWTicketNumberFormartName: function () {
        return { template: FormartName }
      },
      AuToTicketNumberFormartName: function () {
        return { template: AuFormartName }
      },
      SyncroTicketNumberFormartName: function () {
        return { template: syncroFormartName }
      },
      JiraTicketNumberFormartName: function () {
        return { template: jiraFormartName }
      },
      HaloTicketNumberFormartName: function () {
        return { template: haloFormartName }
      },
      TimeFormatName: function () {
        return { template: timeFormat }
      },
      kaseyabmsTicketNumberFormartName: function () {
        return { template: kaseyabmsTicketNumberFormartName }
      },
      recordClomnIndex: 0,
      recordClomn: [],
      customAttributes: { class: 'customcss' },
      wrapSettings: { wrapMode: 'Content' },
      isGridInit: false,
      dataList: [],
      loading: false,
      gadgetHeight: window.innerHeight,
      heightoffset: 60,
      gadgetSetting: {
        showColumnMenu: true,
        allowResizing: true,
        allowFiltering: true,
        filterSettings: { type: 'Excel' },
        allowGrouping: true,
        allowPaging: true,
        allowExcelExport: true,
        allowPdfExport: true,
        toolbar: ['PdfExport', 'CsvExport', 'ColumnChooser'],
        showColumnChooser: true,
        groupOptions: { columns: ['name'] },
        allowReordering: true,
        allowSorting: true,
        allowTextWrap: true,
        height: window.innerHeight - 460,
        pageSettings: { pageSize: 100, pageSizes: [10, 50, 100, 200, 1000], pageCount: 4 },
        groupSettings: {
          allowReordering: false,
          columns: [],
          disablePageWiseAggregates: false,
          enableLazyLoading: false,
          showDropArea: true,
          showGroupedColumn: false,
          showToggleButton: false
        }

      },
      colorMap: [],
      rowArr: {},
      dateKeyList: ['Due Date', 'Last Updated', 'End Time', 'Start Time', 'Expected Resolution Expiration Date', 'Date Entered', 'Assigned User Due Date', 'Expected Resplan Expiration Date', 'Last Time Entry Updated', 'First Response Due Date', 'Expected Response Expiration Date', 'Resolution Plan Date', 'Service Call Start Time', 'Service Call End Time','Date Occurred', 'First Response Date', 'Resolved Due Date','Create Date','Ticket Due Date','Ticket Last Activity Update' ],
      comDataList: {}
    }
  },

  computed: {

  },
  created () {
    this.$root.eventBus.$on('event:selectFormatColumn', (data) => {
      let objData = { [data]: [...new Set(Object.values(this.comDataList.retdata.map(v => v[data])))] }
      this.$emit('updateAllValueList', objData)
    })
    this.comDataList = this.comDataListMethod()
  },
  methods: {
    comDataListMethod () {
      var _self = this
      _self.dataList = _self.nextTicketAllInfo
      var retdata = []
      if (!(_self.dataList && _self.dataList.length > 0)) return false
      _self.dataList.forEach((item, ind) => {
        let obj = {}
        let str = ' '
        if (ind === 0) this.storeClomnLabel(item)
        retdata.push(this.warpData(this.nextTicketType, obj, item, str))
      })
      let columns = []
      if (retdata.length > 0) {
        const isShow = this.$store.state.user.roleList.some(i => i.name === 'Admin')
        Object.keys(retdata[0]).forEach(function (key) {
          if (key === 'MRR' || key === 'MRR Pts') {
            if (isShow) {
              columns.push(key)
            }
          } else {
            columns.push(key)
          }
        })
      }

      if (this.pts && JSON.stringify(this.pts) !== '{}' && (String(this.pts.min) || String(this.pts.max))) {
        let min = String(this.pts.min)
        let max = String(this.pts.max)
        if (min || max) {
          if (min && !max) {
            retdata = this._.filter(retdata, (item) => { return Number(item.Pts) >= Number(min) })
          } else if (!min && max) {
            retdata = this._.filter(retdata, (item) => { return Number(item.Pts) < Number(max) })
          } else if (min && max) {
            if (min === max) retdata = this._.filter(retdata, (item) => { return Number(item.Pts) === Number(max) })
            else retdata = this._.filter(retdata, (item) => { return Number(item.Pts) < Number(max) && Number(item.Pts) >= Number(min) })
          }
        }
      }
      try {
        let arr = JSON.parse(JSON.stringify(columns))
        var ii = 1
        let array = arr.map(item => {
          let res = item.includes('Pts')
          if (res) {
            return {
              key: item,
              color: ii++
            }
          } else {
            return {
              key: item,
              color: ii
            }
          }
        })
        this.colorMap = array
      } catch (error) {

      }
      this.$emit('update:conditionFieldList', columns.filter(v => this.visibleColumn(v)).map(v => {
        return {
          label: v,
          value: v,
          type: 'text'
        }
      }))
      try {
        retdata.forEach(item => {
          for (var key in item) {
            let res = this.nextTicketGadgetSetting.customRuleKeyArray.find(v => v.value.replace('.', '_') === key)
            if (res && (res.type === 'datetime')) {
              item[key] = this.formatDateTime(item[key])
            }
            if (res && (res.type === 'date')) {
              item[key] = this.formatDate(item[key])
            }
          }
        })
      } catch (error) {
      }
      return {
        retdata: retdata,
        columns: columns
      }
    },
    visibleColumn (columnItem) {
      if (columnItem === 'link' || columnItem === 'obj') return false
      else return true
    },
    customAttri (index) {
      if (this.nextTicketType.replace('dataset', '') === 'nextTicket' && index > 4) {
        let ind = Number(index - 6)
        let label = this.recordClomn.find(e => e.index === ind)
        if (label && label.color % 2 === 0) {
          return this.customAttributes
        } else {
          return ''
        }
      } else if (this.nextTicketType.replace('dataset', '') === 'autotask' && index > 5) {
        let ind = Number(index - 8)
        let label = this.recordClomn.find(e => e.index === ind)
        if (label && label.color % 2 === 0) {
          return this.customAttributes
        } else {
          return ''
        }
      } else return '' // TODO syncro
    },
    rowDataBound (args) {
      setTimeout(() => {
        if (this.rowArr[args.row.rowIndex] && this.rowArr[args.row.rowIndex].bgc) {
          args.row.childNodes.forEach(ii => {
            ii.style.backgroundColor = ''
          })
          args.row.style.backgroundColor = this.rowArr[args.row.rowIndex].bgc
        }
        if (this.rowArr[args.row.rowIndex] && this.rowArr[args.row.rowIndex].color) {
          args.row.childNodes.forEach(ii => {
            ii.style.color = this.rowArr[args.row.rowIndex].color
            if (ii.childNodes[0] && ii.childNodes[0].childNodes[0]) {
              ii.childNodes[0].childNodes[0].style.color = this.rowArr[args.row.rowIndex].color
            }
          })
        }
      }, 2000)
    },
    customiseCell (args) {
      try {
        if (args.column.index > this.nextTicketGadgetSetting.columnsIndex) {
          if (this.colorMap[args.column.index].color % 2 === 0) {
            args.cell.style.backgroundColor = '#EDF1F2'
          }
        }
      } catch (error) {

      }

      try {
        var arr = this.ruleList
        var column = args.column.field
        let res = arr.filter(item => {
          if (item.dataForm.filters.rules.length !== 0) {
            return item.dataForm.filters.rules[0].key === column
          }
        })
        if (args.data) {
          res.forEach(it => {
            if (it) {
              let str = ''
              it.dataForm.filters.rules.forEach(ii => {
                // eslint-disable-next-line
                var val = args.data[ii.key].toString()
                if (ii.opt === '==' || ii.opt === '!=') {
                  if (!str) {
                    str += `("${(val).toString()}"  ${ii.opt}   "${(ii.value).toString()}")`
                  } else {
                    if (it.dataForm.filters.condition === 'and') {
                      str += `&& ("${(val).toString()}"  ${ii.opt}   "${(ii.value).toString()}")`
                    } else {
                      str += `|| ("${(val).toString()}"   ${ii.opt}   "${(ii.value).toString()}")`
                    }
                  }
                } else {
                  if (!str) {
                    str += (Number(val) + ii.opt + Number(ii.value))
                  } else {
                    if (it.dataForm.filters.condition === 'and') {
                      str += `&& (${Number(val)}   ${ii.opt}   ${Number(ii.value)})`
                    } else {
                      str += `|| (${Number(val)}   ${ii.opt}   ${Number(ii.value)})`
                    }
                  }
                }
              })
              // eslint-disable-next-line
              let res1 = eval(`${str}`)
              if (res1) {
                if (it.entireRow === 'row') {
                  setTimeout(() => {
                    this.rowArr[args.cell.parentNode.rowIndex] = { bgc: it.backgroundColor, color: it.textColor }
                  }, 500)
                } else {
                  if (args.cell.childNodes[0] && args.cell.childNodes[0].childNodes[0]) {
                    args.cell.childNodes[0].childNodes[0].style.color = it.textColor ? it.textColor : '#000000'
                  }
                  args.cell.style.color = it.textColor ? it.textColor : '#000000'
                  args.cell.style.backgroundColor = it.backgroundColor
                }
              }
            }
          })
        }
      } catch (error) {

      }
    },
    actionComplete (args) {
      if(["columnstate"].includes(args.requestType)){
        this.$refs.datagrid.ej2Instances.componentRefresh()
      }
    },
    dataBound (args) {
      if (!this.isGridInit) {
        this.isGridInit = true
      }
      this.loading = false
    },
    warpData (nextTicketType, obj, item, str) {
      if (nextTicketType.replace('dataset', '') === 'nextTicket') {
        obj = {
          'Ticket  ID': item.id,
          'Ticket  Name': item.entity.summary ? item.entity.summary : null,
          'Pts': item.point,
          // obj: item,
          'Company  Name': item.entity.company ? item.entity.company.name : null,
          'Resource': item.entity.resources ? item.entity.resources : null
        }
      } else if (nextTicketType.replace('dataset', '') === 'syncro') {
        obj = {
          'Ticket Number': item.entity.number,
          'Ticket  Name': item.entity.subject ? item.entity.subject : null,
          'Pts': item.point,
          'Company  Name': item.entity.customer_business_then_name ? item.entity.customer_business_then_name : null,
          'Resource': item.entity.user && item.entity.user.hasOwnProperty('full_name') ? item.entity.user.full_name : null,
          'link': item.entity.link
        }
      } else if (nextTicketType.replace('dataset', '') === 'kaseyabms') {
        obj = {
          'Ticket Number': item.entity.TicketNumber,
          'Title': item.entity.Title,
          'Pts': item.point,
          'Account Name': item.entity.AccountName,
          'Primary Assignee': item.entity.PrimaryAssignee
        }
      } else if (nextTicketType.replace('dataset', '') === 'autotask') {
        obj = {
          'Ticket  Number': item.entity.ticketNumber,
          'Ticket  Name': item.entity.title,
          'Pts': item.point,
          // 'obj': item,
          'Company  ID': item.entity.companyID,
          'Company  Name': item.entity.companyIDName,
          'Resource': item.entity.assignedResourceUserName,
          'link': item.entity.link
        }
      } else if (nextTicketType.replace('dataset', '') === 'jira') {
        obj = {
          'Key': item.entity.key,
          'Summary': item.entity.fields.summary,
          // 'link': item.entity.link,
          'Pts': item.point
        }
      } else if (nextTicketType.replace('dataset', '') === 'halo') {
        obj = {
          'Id': item.entity.id,
          'Summary': item.entity.summary,
          // 'link': item.entity.link,
          'Pts': item.point
        }
      }
      for (let index = 0; index < item.detail.length; index++) {
        const its = item.detail[index]
        let label = its.key
        let keyList = Object.keys(its.value)
        if (keyList.length > 0) {
          for (let i = 0; i < keyList.length; i++) {
            let keys = keyList[i]
            if (obj.hasOwnProperty(keys)) {
              str += '  '
              if (this.dateKeyList.includes(keys)) {
                obj[`${keys}${str}`] = this.formatDateTime(its.value[keys])
              } else obj[`${keys}${str}`] = its.value[keys]
            } else {
              if (this.dateKeyList.includes(keys)) obj[keys] = this.formatDateTime(its.value[keys])
              else obj[keys] = its.value[keys]
            }
          }
        }

        obj[`${label} Pts`] = its.score
      }
      if (nextTicketType.replace('dataset', '') === 'jira') {
        obj.link = item.entity.link
      }
      if (nextTicketType.replace('dataset', '') === 'halo') {
        obj.link = item.entity.link
      }
      if (nextTicketType.replace('dataset', '') === 'kaseyabms') {
        obj.link = item.entity.link
      }
      return obj
    },
    storeClomnLabel (item) {
      this.recordClomnIndex = 0
      this.recordClomn = []
      for (let index = 0; index < item.detail.length; index++) {
        const its = item.detail[index]
        let keyList = Object.keys(its.value)
        if (keyList.length > 0) {
          for (let i = 0; i < keyList.length; i++) {
            this.recordClomn.push({
              index: this.recordClomnIndex,
              color: index
            })
            this.recordClomnIndex++
          }
        }
        this.recordClomn.push({
          index: this.recordClomnIndex,
          color: index
        })
        this.recordClomnIndex++
      }
    },
    formatDateTime (value) {
      return GlobalTimeformat(value, 'HH:mm:ss')
    },
    formatDate (value) {
      return GlobalDateformat(value, 'HH:mm:ss')
    },
    toolbarClick (args) {
      var excelExportProperties = {}
      var arr = JSON.parse(JSON.stringify(this.comDataList.retdata))
      switch (args.item.text) {
        case 'PDF Export':
          let head = JSON.parse(JSON.stringify(this.comDataList.columns)) || []
          let objIndex = head.findIndex(item => item === 'obj')
          head.splice(objIndex, 1)
          head = head.map(item => {
            return {
              alias: item,
              businessType: (item === 'Ticket  ID' || item === 'Ticket  Number') ? 'hyperlinks' : 'text'
            }
          })
          const linkIndex = head.findIndex(i => i.businessType === 'hyperlinks')
          const doc = new JsPDF()
          const body = arr.map(record => {
            for (let key in record) {
              if (linkIndex !== -1 && head[linkIndex].alias === key) {
                if (key === 'Ticket  ID' && this.nextTicketType.replace('dataset', '') === 'nextTicket') { // TODO syncro
                  record.iUrl = 'https://' + store.state.user.domainUrl.cwUrl + '/v4_6_release/ConnectWise.aspx?locale=en_US&routeTo=ServiceFV&recid=' + record['Ticket  ID']
                } else if (key === 'Ticket  Number' && this.nextTicketType.replace('dataset', '') === 'autotask') {
                  record.iUrl = record['link']
                }
                record.iText = record[key].toString()
              }
            }
            return record
          })
          const columns = head.map(i => ({ ...i, header: i.alias, dataKey: linkIndex !== -1 && head[linkIndex].alias === i.alias ? 'iText' : i.alias }))
          doc.autoTable({
            columns,
            body,
            horizontalPageBreak: true,
            styles: { overflow: 'ellipsize', cellWidth: 'wrap' },
            columnStyles: { text: { cellWidth: 'auto' } },
            willDrawCell: (data) => {
              if (data.column.raw.businessType === 'hyperlinks') {
                const { iUrl, iText } = data.row.raw
                data.cell.text = [iText]
                doc.link(data.cell.x, data.cell.y, data.cell.width, data.cell.height, { url: iUrl })
              }
            }

          })
          doc.save('Export.pdf')
          break
        case 'Excel Export':
          try {
            arr.forEach(item => {
              for (var key in item) {
                if (key === 'Ticket  ID' && this.nextTicketType.replace('dataset', '') === 'nextTicket') {
                  let url = 'https://' + store.state.user.domainUrl.cwUrl + '/v4_6_release/ConnectWise.aspx?locale=en_US&routeTo=ServiceFV&recid=' + item['Ticket  ID']
                  item[key] = `<a target='_blank' href='${encodeURIComponent(url)}'>${item[key]}</a>`
                } else if (key === 'Ticket  Number' && this.nextTicketType.replace('dataset', '') === 'autotask') { // TODO syncro
                  item[key] = `<a target='_blank' href='${encodeURIComponent(item['link'])}'>${item[key]}</a>`
                }
              }
            })
          } catch (error) {

          }
          excelExportProperties = {
            dataSource: arr
          }

          this.$refs['datagrid'].excelExport(excelExportProperties)
          break
        case 'CSV Export':
          this.$refs['datagrid'].csvExport(excelExportProperties)
          break
      }
    }

  }

}
</script>

<style lang="scss"  scoped>
.tablecontent {
  padding: 20px;
  ::v-deep .e-filter-popup {
    top: 160px !important;
  }
}
::v-deep .e-grid .e-rowcell.customcss {
  background-color: #edf1f2;
}
::v-deep .e-grid .e-movablecontent {
  // overflow-x: visible;
}
::v-deep .e-grid .e-gridheader .e-sortfilter .e-fltr-icon .e-headercelldiv {
  word-break: break-all;
}
</style>>
